﻿using DevComponents.DotNetBar.SuperGrid;
using SDATA;
using SDLL;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SABI
{
    public partial class frm0106 : Form
    {
        DataTable dt1 = new DataTable();
        IGB igb = new IGB(FRM.ConnectString);
        bool _isNew = true;
        string sql = "";
        string _InventoryID;
        int MethodID = 1;

        public frm0106()
        {
            InitializeComponent();
        }

        public frm0106(bool isNew = true, bool isView = false, string InventoryID = "")
        {
            InitializeComponent();
            _isNew = isNew;
            btnSave.Visible = !isView;
            txtInventoryID.Enabled = isNew;
            btnAdd.Visible = isNew;
            _InventoryID = InventoryID;
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }
               

        void loadDATA_Combo()
        {
            // loại mặt hàng
            sql = "Select * from tb0053 order by InventoryTypeID";
            TDBCboInventoryTypeID.DataSource = FRM.GetDataTable(sql);

            // đơn vị tính
            sql = "Select * from tb0056 order by UnitID";
            TDBCboUnitID.DataSource = FRM.GetDataTable(sql);

            // tài khoản tồn kho
            sql = "Select * from tb0025 Where Disabled =0 and IsNotShow =0 and GroupID in ('G05') Order by AccountID";
            TDBCboAccountID.DataSource = FRM.GetDataTable(sql);

            // tài khoản giá vốn
            sql = "Select * from tb0025 Where Disabled =0 and IsNotShow =0 order by AccountID";
            TDBCboPrimeCostAccountID.DataSource = FRM.GetDataTable(sql);

            // tài khoản bán hàng
            sql = "Select * from tb0025 Where Disabled =0 and IsNotShow =0 and GroupID in ('G04', 'G07') Order by AccountID";
            TDBCboSalesAccountID.DataSource = FRM.GetDataTable(sql);

            // tài khoản mua hàng
            sql = "Select * From tb0025 Where Disabled =0 and IsNotShow =0 and GroupID <> 'G00'  Order by AccountID";
            TDBCboPurchaseAccountID.DataSource = FRM.GetDataTable(sql);

            // 3 mã phân loại
            sql = "Select * From tb0002 Where TableID='tb0054' and IsAutomatic <> 0";
            dt1 = FRM.GetDataTable(sql);

            if(dt1!=null)
            {
                if(dt1.Rows.Count>0)
                {
                    if(dt1.Rows[0]["IsS1"].ToString()=="1" && txtInventoryID.Enabled)
                    {                        
                        sql = "Select S, Sname From tb0062 Where Disabled=0 and StypeID='I01' Order By S";
                        TDBCboSTypeIDI01.Enabled = true;
                        TDBCboSTypeIDI01.DataSource = FRM.GetDataTable(sql);
                        TDBCboSTypeIDI01.SelectedValue = dt1.Rows[0]["S1"].ToString() != "" ? dt1.Rows[0]["S1"].ToString() : "";
                    }
                    if (dt1.Rows[0]["IsS2"].ToString() == "1" && txtInventoryID.Enabled)
                    {
                        sql = "Select S, Sname From tb0062 Where Disabled=0 and StypeID='I02' Order By S";
                        TDBCboSTypeIDI02.Enabled = true;
                        TDBCboSTypeIDI02.DataSource = FRM.GetDataTable(sql);
                        TDBCboSTypeIDI02.SelectedValue = dt1.Rows[0]["S2"].ToString() != "" ? dt1.Rows[0]["S2"].ToString() : "";
                    }
                    if (dt1.Rows[0]["IsS3"].ToString() == "1" && txtInventoryID.Enabled)
                    {
                        sql = "Select S, Sname From tb0062 Where Disabled=0 and StypeID='I03' Order By S";
                        TDBCboSTypeIDI03.Enabled = true;
                        TDBCboSTypeIDI03.DataSource = FRM.GetDataTable(sql);
                        TDBCboSTypeIDI03.SelectedValue = dt1.Rows[0]["S3"].ToString() != "" ? dt1.Rows[0]["S3"].ToString() : "";
                    }
                }
            }

            // nhóm thuế
            sql = "Select * from tb0030 Where Disabled = 0";
            DataTable dt30 = FRM.GetDataTable(sql);
            TDBCboVATGroupID.DataSource = dt30;
            TDBCboVATImGroupID.DataSource = dt30;

            // GridTK
            sql = "Select * From tb0025 Where Disabled =0 and IsNotShow =0 and GroupID in ('G05') Order by AccountID";
            SCBX.GridMultiComboBox gmcb = (SCBX.GridMultiComboBox)GridTK.PrimaryGrid.Columns["clAccountID"].EditControl;
            gmcb.ColumnWidth = new string[] { "120", "150" };
            gmcb.SourceDataString = new string[] { "AccountID", "AccountName" };
            gmcb.SourceDataHeader = new string[] { "Mã tài khoản", "Tên tài khoản" };
            gmcb.StringFilter = "AccountID LIKE '%{0}%'";
            gmcb.DisplayColumnNo = 0;
            gmcb.DataSource = FRM.GetDataTable(sql);

            // GridDT
            sql = "Select * From tb0025 Where Disabled =0 and IsNotShow =0 and GroupID in ('G07') Order by AccountID";
            gmcb = (SCBX.GridMultiComboBox)GridDT.PrimaryGrid.Columns["clAccountID"].EditControl;
            gmcb.ColumnWidth = new string[] { "120", "150" };
            gmcb.SourceDataString = new string[] { "AccountID", "AccountName" };
            gmcb.SourceDataHeader = new string[] { "Mã tài khoản", "Tên tài khoản" };
            gmcb.StringFilter = "AccountID LIKE '%{0}%'";
            gmcb.DisplayColumnNo = 0;
            gmcb.DataSource = FRM.GetDataTable(sql);

        }

        string GenerateInventoryID()
        {            
            if (dt1 == null) { return "" ; }
            if (dt1.Rows.Count == 0) { return ""; }
            
            if (dt1.Rows[0]["IsAutomatic"].ToString() == "1")
            {
                igb.TableName = "tb0054";
                igb.OutputOrder = (IGB.IGEOutputOrder)int.Parse(dt1.Rows[0]["OutputOrder"].ToString() != "" ? dt1.Rows[0]["OutputOrder"].ToString() : "0");
                igb.OutputLength = int.Parse(dt1.Rows[0]["Length"].ToString() != "" ? dt1.Rows[0]["Length"].ToString() : "0");
                if (dt1.Rows[0]["IsS1"].ToString() == "1")
                    igb.StringKey1 = TDBCboSTypeIDI01.Text;
                else
                    igb.StringKey1 = "";
                if (dt1.Rows[0]["IsS2"].ToString() == "1")
                    igb.StringKey2 = TDBCboSTypeIDI02.Text;
                else
                    igb.StringKey2 = "";
                if (dt1.Rows[0]["IsS3"].ToString() == "1")
                    igb.StringKey3 = TDBCboSTypeIDI03.Text;
                else
                    igb.StringKey3 = "";
                igb.SeperatorEnabled = dt1.Rows[0]["IsSeparator"].ToString() == "1" ? true : false;
                if (igb.SeperatorEnabled)
                    igb.SeperatorCharacter = dt1.Rows[0]["Separator"].ToString() != "" ? dt1.Rows[0]["Separator"].ToString() : "";
                else
                    igb.SeperatorCharacter = "";
                if (igb.StringKey1.Length + igb.StringKey2.Length + igb.StringKey3.Length + 3 * igb.SeperatorCharacter.Length >= igb.OutputLength)
                {
                    DLL02.Alert("Độ dài mã hàng vượt quá định dạng cho phép");
                    return "";
                }
                return igb.Generate();

            }
            return "";
        }

        void loadDATA_Edit()
        {
            sql = string.Format("SELECT * FROM tb0054 WHERE InventoryID = '{0}'", _InventoryID);
            DataTable dt = FRM.GetDataTable(sql);
            if (dt == null)
            {
                DLL02.Alert("Dữ liệu bị mất!");
                return;
            }
            else if (dt.Rows.Count == 0)
            {
                DLL02.Alert("Mặt hàng mã: '" + _InventoryID + "' không tồn tại!");
                return;
            }
            txtInventoryID.Text = dt.Rows[0]["InventoryID"].ToString();
            txtInventoryName.Text = dt.Rows[0]["InventoryName"].ToString();
            TDBCboSTypeIDI01.Text = dt.Rows[0]["S1"].ToString();
            TDBCboSTypeIDI02.Text = dt.Rows[0]["S2"].ToString();
            TDBCboSTypeIDI03.Text = dt.Rows[0]["S3"].ToString();
            TDBCboInventoryTypeID.SelectedValue = dt.Rows[0]["InventoryTypeID"].ToString();
            TDBCboUnitID.SelectedValue= dt.Rows[0]["UnitID"].ToString();
            TDBCboAccountID.SelectedValue = dt.Rows[0]["AccountID"].ToString();
            TDBCboSalesAccountID.SelectedValue = dt.Rows[0]["SalesAccountID"].ToString();
            TDBCboPrimeCostAccountID.SelectedValue = dt.Rows[0]["PrimeCostAccountID"].ToString();
            TDBCboPurchaseAccountID.SelectedValue = dt.Rows[0]["PurchaseAccountID"].ToString();
            TDBCboVATGroupID.SelectedValue = dt.Rows[0]["VATGroupID"].ToString();
            txtVATPercent.Text = dt.Rows[0]["VATPercent"].ToString();
            TDBCboVATImGroupID.SelectedValue = dt.Rows[0]["VATImGroupID"].ToString();
            txtVATImPercent.Text = dt.Rows[0]["VATImPercent"].ToString();
            chkIsStocked.Checked = dt.Rows[0]["IsStocked"].ToString() == "1" ? true : false;
            chkIsSource.Checked = dt.Rows[0]["IsSource"].ToString() == "1" ? true : false;
            chkIsLimitDate.Checked = dt.Rows[0]["IsLimitDate"].ToString() == "1" ? true : false;
            chkDisabled.Checked = dt.Rows[0]["Disabled"].ToString() == "1" ? true : false;
            int MethodID = int.Parse(dt.Rows[0]["MethodID"].ToString());
            if (MethodID == 1) { optMethodID01.Checked = true; }
            else if (MethodID == 2) { optMethodID02.Checked = true; }
            else if (MethodID == 3) { optMethodID03.Checked = true; }
            else if (MethodID == 4) { optMethodID04.Checked = true; }
            else if (MethodID == 5) { optMethodID05.Checked = true; }

        }

        void loadDATA_Default()
        {
            TDBCboInventoryTypeID.SelectedValue = FRM.InventoryTypeID;
            TDBCboUnitID.SelectedValue = FRM.UnitID;
            TDBCboVATGroupID.SelectedValue = FRM.VATGroupID;
            TDBCboVATImGroupID.SelectedValue = FRM.VATImGroupID;
            txtVATImPercent.Text = FRM.VATImPercent;
            chkIsSource.Checked = FRM.IsSource;
            chkIsLimitDate.Checked = FRM.IsLimitDate;
            chkIsStocked.Checked = FRM.IsStocked;
            chkDisabled.Checked = false;
            int MethodID = int.Parse(FRM.MethodID);
            if (MethodID == 1) { optMethodID01.Checked = true; }
            else if (MethodID == 2) { optMethodID02.Checked = true; }
            else if (MethodID == 3) { optMethodID03.Checked = true; }
            else if (MethodID == 4) { optMethodID04.Checked = true; }
            else if (MethodID == 5) { optMethodID05.Checked = true; }
        }

        private void frm0106_Shown(object sender, EventArgs e)
        {
            loadDATA_Combo();
            loadDATA_Default();
            if (!txtInventoryID.Enabled) { loadDATA_Edit(); }
        }        

        private void TDBCboInventoryTypeID_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtInventoryTypeName.Text = TDBCboInventoryTypeID.SelectedItem != null ? TDBCboInventoryTypeID.SelectedItem.ItemData[1] : "";
        }

        private void TDBCboUnitID_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtUnitName.Text = TDBCboUnitID.SelectedItem != null ? TDBCboUnitID.SelectedItem.ItemData[1] : "";
        }

        private void TDBCboAccountID_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtAccountName.Text = TDBCboAccountID.SelectedItem != null ? TDBCboAccountID.SelectedItem.ItemData[1] : "";
        }

        private void TDBCboSalesAccountID_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtSalesAccountID.Text = TDBCboSalesAccountID.SelectedItem != null ? TDBCboSalesAccountID.SelectedItem.ItemData[1] : "";
        }

        private void TDBCboPrimeCostAccountID_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtPrimeCostAccountID.Text = TDBCboPrimeCostAccountID.SelectedItem != null ? TDBCboPrimeCostAccountID.SelectedItem.ItemData[1] : "";
        }

        private void TDBCboPurchaseAccountID_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtPurchaseAccountName.Text = TDBCboPurchaseAccountID.SelectedItem != null ? TDBCboPurchaseAccountID.SelectedItem.ItemData[1] : "";
        }

        private void TDBCboVATGroupID_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtVATPercent.Text = TDBCboVATGroupID.SelectedItem != null ? TDBCboVATGroupID.SelectedItem.ItemData[2] : "0";
        }

        private void TDBCboVATImGroupID_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtVATImPercent.Text = TDBCboVATImGroupID.SelectedItem != null ? TDBCboVATImGroupID.SelectedItem.ItemData[2] : "0";
        }

        private void chkIstock_CheckedChanged(object sender, EventArgs e)
        {
            fraInvmanager.Enabled = chkIsStocked.Checked;
            fraDeliveryMothod.Enabled = chkIsStocked.Checked;
        }

        bool CheckInput()
        {
            if(txtInventoryID.Text.Trim()=="")
            {
                DLL02.Alert("Mã mặt hàng không được để trống");
                return false;
            }
            else if(txtInventoryName.Text.Trim()=="")
            {
                DLL02.Alert("Tên mặt hàng không được để trống");
                return false;
            }
            return true;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            // hỏi trước khi lưu
            if(FRM.AskBeforeSave)
                if (!DLL02.Confirm("Bạn có chắc muốn lưu?", "Xác nhận")) { return; }

            // kiểm tra nhập
            if (!CheckInput()) { return; }

            
            if(optMethodID02.Checked){MethodID = 2;}
            if(optMethodID03.Checked){MethodID = 3;}
            if(optMethodID04.Checked){MethodID = 4;}
            if(optMethodID05.Checked){MethodID = 5;}

            if (txtInventoryID.Enabled)
                SaveDATA();
            else
                EditDATA();
            
        }

        void SaveDATA()
        {
            sql = " Insert Into tb0054(InventoryID,InventoryName,InventoryTypeID, UnitID,";
            sql += " AccountID,SalesAccountID, PrimeCostAccountID, PurchaseAccountID,";
            sql += " VATGroupID, VATPercent, DivisionID, GroupShow, ";
            sql += " MethodID,VATImGroupID,VATImPercent,";
            sql += " IsSource, IsLimitDate, IsStocked,";
            sql += " S1,S2,S3, Disabled,";
            sql += " CreateUserID,CreateDate,LastModifyUserID,LastModifyDate) VALUES(";
            sql += string.Format("'{0}',N'{1}','{2}','{3}',", txtInventoryID.Text, txtInventoryName.Text, TDBCboInventoryTypeID.Text, TDBCboUnitID.Text);
            sql += string.Format("'{0}','{1}','{2}','{3}',", TDBCboAccountID.Text, TDBCboSalesAccountID.Text, TDBCboPrimeCostAccountID.Text, TDBCboPurchaseAccountID.Text);
            sql += string.Format("'{0}','{1}','{2}','{3}', ", TDBCboVATGroupID.Text, txtVATPercent.Text, FRM.DivisionID, FRM.ID_Group);
            sql += string.Format("'{0}','{1}','{2}',", MethodID, TDBCboVATImGroupID.Text, txtVATImPercent.Text);
            sql += string.Format("'{0}','{1}','{2}',", chkIsSource.Checked ? 1 : 0, chkIsLimitDate.Checked ? 1 : 0, chkIsStocked.Checked ? 1 : 0);
            sql += string.Format("'{0}','{1}','{2}','{3}',", TDBCboSTypeIDI01.Text, TDBCboSTypeIDI02.Text, TDBCboSTypeIDI03.Text, chkDisabled.Checked ? 1 : 0);
            sql += string.Format("'{0}',GETDATE(),'{0}',GETDATE())", FRM.UserName);

            if (DATA.ExecuteNonQuery(sql, FRM.ConnectString, true))
            {
                if (!txtInventoryID.ReadOnly) { igb.SaveNewKey(); }
                DLL02.Info("Lưu dữ liệu thành công!");
                (Application.OpenForms["frm0096"] as frm0096).loadDATA_Grid1();
                //btnSave.Enabled = false;
                txtInventoryID.Enabled = false;
                TDBCboSTypeIDI01.Enabled = false;
                TDBCboSTypeIDI02.Enabled = false;
                TDBCboSTypeIDI03.Enabled = false;
            }
            else
            {
                SDLL.DLL02.Alert("Lưu dữ liệu thất bại!");
            }
        }

        void EditDATA()
        {
            sql = string.Format("UPDATE tb0054 SET InventoryName=N'{0}',InventoryTypeID='{1}', UnitID='{2}',", txtInventoryName.Text, TDBCboInventoryTypeID.Text, TDBCboUnitID.Text);
            sql += string.Format("AccountID='{0}',SalesAccountID='{1}', PrimeCostAccountID='{2}', PurchaseAccountID='{3}',", TDBCboAccountID.Text, TDBCboSalesAccountID.Text, TDBCboPrimeCostAccountID.Text, TDBCboPurchaseAccountID.Text);
            sql += string.Format("VATGroupID='{0}', VATPercent='{1}',", TDBCboVATGroupID.Text, txtVATPercent.Text);
            sql += string.Format("MethodID='{0}',VATImGroupID='{1}',VATImPercent='{2}',", MethodID, TDBCboVATImGroupID.Text, txtVATImPercent.Text);
            sql += string.Format("IsSource='{0}', IsLimitDate='{1}', IsStocked='{2}',", chkIsSource.Checked ? 1 : 0, chkIsLimitDate.Checked ? 1 : 0, chkIsStocked.Checked ? 1 : 0);
            sql += string.Format("S1='{0}',S2='{1}',S3='{2}', Disabled='{3}',", TDBCboSTypeIDI01.Text, TDBCboSTypeIDI02.Text, TDBCboSTypeIDI03.Text, chkDisabled.Checked ? 1 : 0);
            sql += string.Format("LastModifyUserID='{0}',LastModifyDate=GETDATE() WHERE InventoryID = '{1}' ", FRM.UserName, txtInventoryID.Text);

            if (DATA.ExecuteNonQuery(sql, FRM.ConnectString, true))
            {
                DLL02.Info("Cập nhật dữ liệu thành công!");
                (Application.OpenForms["frm0096"] as frm0096).loadDATA_Grid1();
                Close();
            }
            else
            {
                SDLL.DLL02.Alert("Cập nhật dữ liệu thất bại!");
            }
        }

        private void TDBCboSTypeIDI01_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtInventoryID.Text = GenerateInventoryID();
        }

        private void TDBCboSTypeIDI02_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtInventoryID.Text = GenerateInventoryID();
        }

        private void TDBCboSTypeIDI03_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtInventoryID.Text = GenerateInventoryID();
        }

        private void frm0106_Load(object sender, EventArgs e)
        {

        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            loadDATA_Combo();
            loadDATA_Default();
            txtInventoryID.Enabled = true;
            txtInventoryID.ReadOnly = false;
            txtInventoryName.Text = "";
            btnSave.Enabled = true;
            TDBCboAccountID.Clear();
            TDBCboPrimeCostAccountID.Clear();
            TDBCboPurchaseAccountID.Clear();
            TDBCboSalesAccountID.Clear();
        }

        private void GridTK_EndEdit(object sender, DevComponents.DotNetBar.SuperGrid.GridEditEventArgs e)
        {
            SCBX.GridMultiComboBox gmcb = (SCBX.GridMultiComboBox)GridTK.PrimaryGrid.Columns["clAccountID"].EditControl;
            if (gmcb.SelectedItem == null) { return; }
            GridRow gr = (GridRow)e.GridPanel.ActiveRow;
            gr.Cells["clAccountName"].Value = gmcb.SelectedItem.ItemData[1];
        }

        private void GridDT_EndEdit(object sender, GridEditEventArgs e)
        {
            SCBX.GridMultiComboBox gmcb = (SCBX.GridMultiComboBox)GridDT.PrimaryGrid.Columns["clAccountID"].EditControl;
            if (gmcb.SelectedItem == null) { return; }
            GridRow gr = (GridRow)e.GridPanel.ActiveRow;
            gr.Cells["clAccountName"].Value = gmcb.SelectedItem.ItemData[1];
        }



    }
}
